package com.yjz.jvm.juc.countdownlanch;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class CountDownLatchLearn {
  /**
   * 初始化countdownlatch,有几个子线程就给几
   */
  private static CountDownLatch latch = new CountDownLatch(1);

  public static void main(String[] args) throws InterruptedException {

    Thread th = new Thread(() -> {
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      log.info("子线程启动");
      /*子线程运行完毕之后将计数减一*/
      latch.countDown();

    }, "子线程");

    th.start();
		/*主线程必须在启动其他线程后(th.start())立即调用CountDownLatch.await()方法。
		这样主线程的操作就会在这个方法上阻塞，直到其他线程完成各自的任务。（重要）*/

    /*调用await的线程会被挂起，它会等待直到count值为0才继续执行*/
    latch.await();
    /*线程调用join()方法,则主线程会等待子线程执行完再执行*/
//		th.join();
    Thread.sleep(2000);

    log.info("子线程将countdownlatch的计数置为0,主线程启动");
  }


}
